<template>
    <view class="pt-[14rpx] px-[98rpx] bg-[#F3F5F9]">
        <view class="flex justify-center">
            <image src="@/static/images/img/cwgt.png" class="w-[108rpx] h-[108rpx]"></image>
        </view>
        <view class="mt-[10rpx] flex justify-center">请补充宠物信息</view>
        <view class="mt-[14rpx] flex flex-col justify-center items-center">
            <avatar-upload :size="156" rounded="50%" text_mag="上传头像" @update:modelValue="change" :modelValue="formData.avatar" :isAvatar="false" />
            <view class="mt-[14rpx]">请上传头像</view>
        </view>
        
        <!-- 宠物名称 -->
        <view class="mt-[34rpx]">
            <text class="text-[28rpx] text-[#000000] font-[PingFang SC] font-[500]">宝贝叫什么？</text>
			<view class="h-[80rpx] mt-[10rpx]">
				<up-input
					v-model="formData.name"
					placeholder="请输入宠物名称"
					border="none"
					shape="circle"
                    :customStyle="{
                        backgroundColor: '#FFFFFF',
                        height: '40px',
                        padding: '12rpx',
                        paddingLeft: '42rpx',
                        fontSize: '25rpx'
                    }"
				></up-input>
			</view>
        </view>
         
        <!-- 宠物类型 -->
        <view class="mt-[24rpx]">
            <text class="text-[28rpx] text-[#000000] font-[PingFang SC] font-[500]">宝贝是什么类型？</text>
			<view class="h-[80rpx] mt-[10rpx]">
				<up-input
					v-model="formData.type"
					placeholder="请选择宠物类型"
					border="none"
					shape="circle"
                    :customStyle="{
                        backgroundColor: '#FFFFFF',
                        height: '40px',
                        padding: '12rpx',
                        paddingLeft: '42rpx',
                        fontSize: '25rpx'
                    }"
				></up-input>
			</view>
        </view>
            
        <!-- 宠物性别 -->
        <view class="mt-[24rpx] ">
            <text class="text-[28rpx] text-[#000000] font-[500]">宝贝是弟弟/妹妹？</text>
            <view class="flex mt-[16rpx] gap-[20rpx]">
                <view 
                    class="flex-1 h-[80rpx] rounded-full flex items-center justify-center text-[28rpx]"
                    :class="formData.sex === 0 ? 'bg-black text-white' : 'bg-white text-[#999]'"
                    @click="selectSex(0)"
                >
                    弟弟
                </view>
                <view 
                    class="flex-1 h-[80rpx] rounded-full flex items-center justify-center text-[28rpx]"
                    :class="formData.sex === 1 ? 'bg-black text-white' : 'bg-white text-[#999]'"
                    @click="selectSex(1)"
                >
                    妹妹
                </view>
            </view>
        </view>
            
        <!-- 宠物生日 -->
        <view class="mt-[24rpx] ">
            <text class="text-[28rpx] text-[#000000] font-[500]">宝贝的生日是什么时候？</text>
            <view class="date-picker mt-[16rpx]" @click="showDatePicker = true">
                <view class="bg-white rounded-full h-[80rpx] flex items-center px-[42rpx] text-[28rpx]" :class="formData.birthday ? 'text-[#333]' : 'text-[#999]'">
                    <text>{{ formData.birthday || '请选择生日' }}</text>
                    <view class="absolute right-[30rpx]">
                        <image src="@/static/images/img/xia.png" class="w-[36rpx] h-[20rpx]"></image>
                    </view>
                </view>
            </view>
            
            <!-- 日期选择器 -->
            <up-datetime-picker
                :show="showDatePicker"
                v-model="dateValue"
                mode="date"
                @cancel="showDatePicker = false"
                @confirm="onDateConfirm"
                :minDate="minDate"
                :maxDate="maxDate"
            />
        </view>
            
        <!-- 绑定设备 -->
        <view class="mt-[24rpx] flex items-center ]">
            <text class="text-[28rpx] text-[#000000] font-[500]">绑定设备</text>
            <text class="text-[24rpx] text-[#999] ml-[10rpx]">(非必填)</text>
            <view @click="scan" class="ml-auto">
                <text class="text-[28rpx] text-[#3366FF]">+扫码添加</text>
            </view>
        </view>
        <view class="h-[80rpx] mt-[16rpx] relative ">
            <view class="bg-white rounded-full h-[100rpx] flex items-center px-[42rpx] text-[28rpx] text-[#999]">
                <up-input
					v-model="formData.clientId"
					placeholder="请输入设备号"
					border="none"
					shape="circle"
                    :customStyle="{
                        backgroundColor: '#FFFFFF',
                        height: '40px',
                        padding: '12rpx',
                        paddingLeft: '42rpx',
                        fontSize: '25rpx'
                    }"
				></up-input>
            </view>
        </view>
            
        <!-- 添加按钮 -->
        <view class="mt-[80rpx] mb-[40rpx]" @click="submitForm">
           
            <image src="@/static/images/img/tj.png" class="w-[538rpx] h-[108rpx] mt-[10rpx]"></image>
        </view>
    </view>
</template>

<script setup>
import { ref } from 'vue';
import { addPet } from '@/api/pet';

import useUserStore from '@/store/modules/user';
import { parseTime } from '@/utils/ruoyi.js';
const userStore = useUserStore();

// 表单数据
const formData = ref({
    name: '',
    avatar: '',
    sex: '', // 0表示弟弟，1表示妹妹
    birthday: '',
    type: '',
    clientId: null,
});

// 日期选择器相关
const showDatePicker = ref(false);
const dateValue = ref(new Date().getTime()); // 当前日期作为默认值
const minDate = new Date(new Date().getFullYear() - 30, 0, 1).getTime(); // 30年前
const maxDate = new Date().getTime(); // 今天

// 日期选择确认
const onDateConfirm = (e) => {
    console.log('选择的日期:', e);
    showDatePicker.value = false;
    dateValue.value = e.value;
    
    // 格式化日期为 YYYY-MM-DD
    const date = new Date(e.value);
    const year = date.getFullYear();
    const month = String(date.getMonth() + 1).padStart(2, '0');
    const day = String(date.getDate()).padStart(2, '0');
    formData.value.birthday = `${year}-${month}-${day}`;
};

// 头像上传回调
const change = (e) => {
    formData.value.avatar = e;
};

// 选择性别
const selectSex = (sex) => {
    formData.value.sex = sex;
};
// 扫码添加设备
const scan = () => {
    uni.scanCode({
        success: (res) => {
            console.log('扫码结果:', res);
            formData.value.clientId = res.result;
        },
        fail: (err) => {
            console.log('扫码失败:', err);
        }
    });
}
// 提交表单
const submitForm = () => {
    // 表单验证
    if (!formData.value.name) {
        uni.showToast({
            title: '请输入宠物名称',
            icon: 'none'
        });
        return;
    }
    if (!formData.value.avatar) {
        uni.showToast({
            title: '请上传宠物头像',
            icon: 'none'
        });
        return;
    }
    
    if (!formData.value.type) {
        uni.showToast({
            title: '请选择宠物类型',
            icon: 'none'
        });
        return;
    }
    
    if (formData.value.sex === '') {
        uni.showToast({
            title: '请选择宠物性别',
            icon: 'none'
        });
        return;
    }
    
    if (!formData.value.birthday) {
        uni.showToast({
            title: '请选择宠物生日',
            icon: 'none'
        });
        return;
    }
    
    // 提交数据
    console.log('提交的宠物信息:', formData.value);
    formData.value.birthday = parseTime(formData.value.birthday, '{y}-{m}-{d} {h}:{i}:{s}');
    // 显示加载中
    uni.showLoading({
        title: '添加中...',
        
    });
    
    // 调用API接口提交数据
    uni.$u.throttle(()=>{addPet(formData.value).then(res => {
        uni.hideLoading();
        if (res.code === 200) {
            uni.showToast({
                title: '添加成功',
                icon: 'success'
            });
            
            // 添加成功后返回上一页
            setTimeout(() => {
                uni.navigateBack();
            }, 1500);
        } else {
            uni.showToast({
                title: res.msg || '添加失败',
                icon: 'none'
            });
        }
    }).catch(err => {
        uni.hideLoading();
        uni.showToast({
            title: '网络异常，请稍后重试',
            icon: 'none'
        });
        console.error('添加宠物失败:', err);
    });},5000, false)
    
};
</script>

<style scoped lang="scss">
.date-picker {
    position: relative;
    
    .date-display {
        display: flex;
        justify-content: space-between;
        align-items: center;
        padding: 15rpx 20rpx;
        background-color: #fff;
        border-radius: 100rpx;
        font-size: 28rpx;
    }
}
</style>